//
//  NewFeatureView.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/2/28.
//  Copyright © 2016年 蔡杰. All rights reserved.
//
private let CZNewFeatureImageCount = 4

import UIKit

class NewFeatureView: UIView {

   override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
          setNewfattureUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    private lazy var pageControl = UIPageControl()

}

extension NewFeatureView {


    private func setNewfattureUI (){
    
        backgroundColor = UIColor.whiteColor()
    
        let scrollView = UIScrollView(frame: bounds)
        
        addSubview(scrollView)
        scrollView.contentSize = CGSize(width: bounds.width * CGFloat(CZNewFeatureImageCount + 1), height: 0)
        
        for i in 0..<CZNewFeatureImageCount {
        
            let imageView = UIImageView(image: UIImage(named: "new_feature_\((i+1))"))
            
            scrollView.addSubview(imageView)
            
            imageView.frame = CGRectOffset(bounds, scrollView.frame.size.width * CGFloat(i), 0)
        }
        
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.pagingEnabled = true
        
        // 6. 设置分页控件
        addSubview(pageControl)
        
        pageControl.hidesForSinglePage = true
        pageControl.numberOfPages = CZNewFeatureImageCount
        pageControl.currentPage = 0
        pageControl.pageIndicatorTintColor = UIColor.blackColor()
        pageControl.currentPageIndicatorTintColor = CZAppearanceTintColor
        // 禁用交互
        pageControl.userInteractionEnabled = false

        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-80)
        }
        scrollView.delegate = self
    }
}

extension NewFeatureView :UIScrollViewDelegate{

    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 1. 计算当前所在页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 2. 如果是最后一页，销毁当前视图
        if page == CZNewFeatureImageCount {
            removeFromSuperview()
        }
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5 )
        pageControl.currentPage = page
        
        pageControl.hidden = (page == CZNewFeatureImageCount)
        
        
    }
}